import React, { useState, useEffect } from 'react';
import { Button, Drawer, Form, FormInstance } from 'antd';
import { Node } from '@antv/x6';
import SearchBase, { ItemProps } from '../SearchBase';
import { nextTick } from '../../tools';
import { getDefaultItems } from './tools';

interface CreateNodeProps {
  visible?: boolean;
  onClose: () => void;
  onSubmit?: (nodeData: any) => Promise<boolean>;
  node?: Node;
  onLoad?: (form: FormInstance) => void;
  laneOptions: SelectOption[];
}

const CreateNode: React.FC<CreateNodeProps> = function ({
  visible,
  onClose,
  onSubmit,
  onLoad,
  node,
  laneOptions = [],
}) {
  const [form] = Form.useForm();
  const [items, setItems] = useState<ItemProps[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  useEffect(() => {
    onLoad && onLoad(form);
  }, []);

  function getSupportLaneOptions(
    laneOptions: SelectOption[],
    target?: string[],
  ) {
    if (!Array.isArray(target) || !target.length) {
      return laneOptions;
    }
    const lanesMap = laneOptions.reduce((p, c) => {
      p[c.value as string] = c;
      return p;
    }, {});
    return target.map((l) => lanesMap[l]);
  }

  useEffect(() => {
    if (!visible) return;
    if (!node) {
      setItems([]);
    } else {
      const { data } = node;
      const moduleProps = (window as any)._moduleProps || {};
      const modules = (window as any)._modules || {};
      const { moduleType, target } = data;
      const modulePropItems = [
        ...getDefaultItems(
          getSupportLaneOptions(laneOptions, target),
          Object.values(modules),
          !!node?.data?.id,
        ),
        ...(moduleProps[moduleType] || []),
      ];
      const initValue = modulePropItems.reduce((p, c) => {
        p[c.name] = data[c.name];
        return p;
      }, {});
      setItems(modulePropItems);
      nextTick(() => form.setFieldsValue(initValue));
    }
  }, [visible, node, laneOptions]);

  const submitForm = () => {
    form.validateFields().then(async (values: any) => {
      setLoading(true);
      if (onSubmit) {
        const copyNode = node!.clone();
        copyNode.setData(values);
        const ret = await onSubmit(copyNode);
        setLoading(false);
        if (ret) onClose();
      } else {
        setLoading(false);
        onClose();
      }
    });
  };

  return (
    <Drawer
      title={`${node?.data?.id ? '编辑' : '新建'}节点`}
      placement="right"
      className="ra-arch-createNode"
      closable={false}
      onClose={onClose}
      visible={visible}
      getContainer={() => document.body}
      extra={
        <Button
          loading={loading}
          type="primary"
          ghost
          size="small"
          onClick={submitForm}
        >
          提交
        </Button>
      }
    >
      <SearchBase form={form} items={items} />
    </Drawer>
  );
};

export default CreateNode;
